<template>
	<view class="novel-content" @click="handleClick" :style="{ backgroundColor: comStore.pageColor}">
		<view v-if="loading" class="loading-overlay " :style="{ backgroundColor: comStore.pageColor}">
			<view class="loading-content">
				<text>加载中 {{ textLayoutStore?.loadingProgress || 0 }}%</text>
			</view>
		</view>
		<template v-else>
			<view class="chapter-title">
				<text
					:style="{ color: comStore.fontColor}">{{ textLayoutStore?.currentChapterInfo?.title || '' }}</text>
			</view>
			<text class="context" :class="{ 'glass-effect': comStore.iseffect}"
				:style="textStyle">{{ currentPageContent }}</text>
			<view class="reading-progress">
				<text :style="{ color: comStore.fontColor}">{{ textLayoutStore?.readingProgress || 0 }}%</text>
				<view style="display: flex;">
					<text>{{currentTime}} | {{batteryLevel}}%</text>
				</view>
			</view>
		</template>
	</view>
	<Menu ref="menuRef" v-show="store.isMenu" />
	<Catalogue v-show="store.isCatalogue" />
	<Brightness v-show="store.isBrightness" />
	<Voiceread v-show="store.isVoiceread" />
	<Readsetting v-show="store.isReadsetting" @font-size-change="handleFontSizeChange" />
	<Timing v-show="store.isTiming" />
	<Pageway v-show="store.isPageway" />
</template>

<script setup>
	import Menu from '../../component/novel/menu.vue';
	import Catalogue from '../../component/novel/catalogue.vue';
	import Brightness from '../../component/novel/brightness.vue';
	import Voiceread from '../../component/novel/voiceread.vue';
	import Readsetting from '../../component/novel/readsetting.vue';
	import Timing from '../../component/novel/timing.vue';
	import Pageway from '../../component/novel/pageway.vue';
	import {
		ref,
		onMounted,
		nextTick,
		computed,
		watch,
		getCurrentInstance,
		onBeforeMount
	} from 'vue';
	import {
		useNovelStore
	} from '../../common/novel/novel.js';
	import {
		useTextLayoutStore
	} from '../../common/novel/textLayout.js';
	import {
		useComStore
	} from '../../common/common.js'
	import {
		useVoiceReadStore
	} from '../../common/love/leason.js';

	// 初始化 Pinia 仓库
	const store = useNovelStore();
	const textLayoutStore = useTextLayoutStore();
	const comStore = useComStore();
	const voiceReadStore = useVoiceReadStore();

	// 定义refs
	const menuRef = ref(null);
	// 计算样式
	const textStyle = computed(() => ({
		fontSize: `${textLayoutStore.fontSize}px`,
		lineHeight: `${textLayoutStore.lineHeight*textLayoutStore.fontSize}px`,
		// padding: `${textLayoutStore.marginVertical}px ${textLayoutStore.marginHorizontal}px`,
		// 'margin-top': `${textLayoutStore.lineSpace}px`,
		width: `${textLayoutStore.availableWidth}px`,
		height: `${textLayoutStore.availableHeight}px`,
		color: `${comStore.fontColor}`
	}));

	// 获取当前页内容
	const currentPageContent = computed(() => textLayoutStore.getCurrentPageContent());

	// 添加加载状态
	const loading = ref(true);

	// 在 read.vue 中添加接收路径参数
	const novelPath = ref('');

	const instance = getCurrentInstance();

	onBeforeMount(() => {
		// 获取页面参数
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.$page?.options || {};
		if (options.path) {
			// 解码 URL 编码的路径
			novelPath.value = decodeURIComponent(options.path);
			// console.log('接收到的小说路径：', novelPath.value);
		}
	});

	// 监听加载完成
	watch(() => textLayoutStore.loadingProgress, (progress) => {
		if (progress >= 100) {
			loading.value = false;
		}
	});


	const currentTime = ref('00:00')

	// 更新时间函数
	const updateTime = () => {
		const date = new Date()
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')
		currentTime.value = `${hours}:${minutes}`
	}

	const batteryLevel = ref(100)
	const isCharging = ref(false)

	// 获取电量信息
	const getquantity = () => {
		// 直接尝试使用Android原生接口
		// #ifdef APP-PLUS
		if (plus && plus.android) {
			try {
				getAndroidBatteryLevel();
				return;
			} catch (err) {
				console.error('Android原生接口获取电量失败:', err);
				showDetailedError('Android原生接口调用失败', err);
			}
		}
		// #endif
		
		// 如果不是App环境或plus方法失败，尝试其他方法
		tryOtherMethods();
	};

	// 使用Android原生接口获取电量
	const getAndroidBatteryLevel = () => {
		// #ifdef APP-PLUS
		try {
			// 尝试方法1: 使用BatteryManager
			const main = plus.android.runtimeMainActivity();
			const Intent = plus.android.importClass('android.content.Intent');
			const IntentFilter = plus.android.importClass('android.content.IntentFilter');
			
			// 记录详细日志
			console.log('开始尝试Android原生接口获取电量');
			console.log('main对象:', main ? '存在' : '不存在');
			
			// 尝试导入BatteryManager类
			try {
				const BatteryManager = plus.android.importClass('android.os.BatteryManager');
				console.log('成功导入BatteryManager类');
				
				const intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
				const batteryStatus = main.registerReceiver(null, intentFilter);
				
				if (batteryStatus) {
					const level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
					const scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
					const status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
					
					console.log('原始电量数据:', {level, scale, status});
					
					if (level >= 0 && scale > 0) {
						const batteryLevelValue = Math.floor((level / scale) * 100);
						const isChargingValue = status === BatteryManager.BATTERY_STATUS_CHARGING || 
										  status === BatteryManager.BATTERY_STATUS_FULL;
						
						batteryLevel.value = batteryLevelValue;
						isCharging.value = isChargingValue;
						return true;
					} else {
						console.error('获取的电量值无效:', {level, scale});
					}
				} else {
					console.error('batteryStatus为null');
				}
			} catch (err) {
				console.error('BatteryManager方法失败:', err);
				// 尝试方法2
			}
			
			// 尝试方法2: 使用Context.BATTERY_SERVICE (Android 5.0+)
			try {
				console.log('尝试使用Context.BATTERY_SERVICE');
				const Context = plus.android.importClass('android.content.Context');
				const BatteryManager = plus.android.importClass('android.os.BatteryManager');
				
				const batteryManager = main.getSystemService(Context.BATTERY_SERVICE);
				if (batteryManager) {
					const batteryLevelValue = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
					const isChargingValue = batteryManager.isCharging();
					
					console.log('BATTERY_SERVICE获取的数据:', {batteryLevelValue, isChargingValue});
					
					if (batteryLevelValue >= 0) {
						batteryLevel.value = batteryLevelValue;
						isCharging.value = isChargingValue;
						return true;
					}
				} else {
					console.error('batteryManager为null');
				}
			} catch (err) {
				console.error('Context.BATTERY_SERVICE方法失败:', err);
			}
			
			// 尝试方法3: 使用系统设置
			try {
				console.log('尝试使用Settings.System');
				const Settings = plus.android.importClass('android.provider.Settings');
				const System = plus.android.importClass('android.provider.Settings$System');
				const contentResolver = main.getContentResolver();
				
				// 检查是否有权限读取系统设置
				const canReadSettings = Settings.System.canWrite(main);
				console.log('是否有权限读取系统设置:', canReadSettings);
				
				if (canReadSettings) {
					const batteryLevelValue = System.getInt(contentResolver, "status_battery_level", -1);
					console.log('系统设置获取的电量:', batteryLevelValue);
					
					if (batteryLevelValue >= 0) {
						batteryLevel.value = batteryLevelValue;
						isCharging.value = false; // 无法确定充电状态
						return true;
					}
				}
			} catch (err) {
				console.error('Settings.System方法失败:', err);
			}
			
			return false;
		} catch (err) {
			console.error('Android原生接口总体失败:', err);
			return false;
		}
		// #endif
		
		return false;
	};

	// 尝试其他方法
	const tryOtherMethods = () => {
		// 使用getSystemInfo
		uni.getSystemInfo({
			success: (res) => {
				console.log('系统信息:', res);
				
				// 尝试从系统信息中获取电量
				if (typeof res.battery === 'number' && res.battery >= 0) {
					batteryLevel.value = res.battery;
					isCharging.value = !!res.isCharging;
				} else if (typeof navigator !== 'undefined' && navigator.getBattery) {
					// 使用Web Battery API
					navigator.getBattery().then(battery => {
						batteryLevel.value = Math.floor(battery.level * 100);
						isCharging.value = battery.charging;
					}).catch((err) => {
						console.error('Web Battery API 失败:', err);
						showDetailedError('所有获取电量方法均失败', null);
					});
				} else {
					showDetailedError('所有获取电量方法均失败', null);
				}
			},
			fail: (err) => {
				console.error('getSystemInfo 失败:', err);
				showDetailedError('获取系统信息失败', err);
			}
		});
	};

	// 显示详细错误信息
	const showDetailedError = (title, err) => {
		// 收集详细的错误信息
		let errorDetails = "";
		if (err) {
			if (typeof err === 'object') {
				try {
					errorDetails = JSON.stringify(err, Object.getOwnPropertyNames(err), 2);
				} catch (e) {
					errorDetails = err.toString();
				}
			} else {
				errorDetails = String(err);
			}
		}
		
		// 收集可用API信息
		let apiInfo = "\n\nAPI可用性:\n";
		
		// #ifdef APP-PLUS
		if (typeof plus !== 'undefined') {
			apiInfo += "- plus: 可用\n";
			apiInfo += "  - plus.android: " + (plus.android ? "可用" : "不可用") + "\n";
			if (plus.android) {
				try {
					const androidVersion = plus.os.version;
					apiInfo += "  - Android版本: " + androidVersion + "\n";
				} catch (e) {
					apiInfo += "  - Android版本: 获取失败\n";
				}
			}
		} else {
			apiInfo += "- plus: 不可用\n";
		}
		// #endif
		
		apiInfo += "- uni.getBatteryInfo: " + (uni.getBatteryInfo ? "存在" : "不存在") + "\n";
		apiInfo += "- navigator.getBattery: " + 
			(typeof navigator !== 'undefined' && navigator.getBattery ? "存在" : "不存在") + "\n";
		
		// 显示错误信息
		uni.showModal({
			title: '无法获取电量',
			content: `${title}。\n\n${errorDetails ? '错误详情:\n' + errorDetails + '\n\n' : ''}${apiInfo}`,
			showCancel: false
		});
	};

	// 生命周期钩子 - 组件挂载后执行
	onMounted(async () => {
		try {
			loading.value = true;
			console.log('开始初始化页面');

			// #ifdef APP-PLUS
			// 检查并请求权限
			const checkAndRequestPermission = () => {
				return new Promise((resolve, reject) => {
					plus.android.requestPermissions(
						['android.permission.READ_EXTERNAL_STORAGE'],
						function(resultObj) {
							resolve(resultObj.granted.length > 0);
						},
						function(error) {
							reject(error);
						}
					);
				});
			};

			try {
				await checkAndRequestPermission();
			} catch (error) {
				console.error('权限请求失败:', error);
			}

			// 更新屏幕尺寸
			await textLayoutStore.initLayout();

			// 根据不同路径使用不同的加载方式
			if (novelPath.value && novelPath.value.startsWith('_doc')) {
				// console.log('开始加载自定义小说：', novelPath.value);
				const filePath = plus.io.convertLocalFileSystemURL(novelPath.value);
				console.log('转换后的文件路径：', filePath);

				try {
					// 先尝试从缓存加载
					const cacheKey = `novel_${filePath.split('/').pop()}`;
					const cachedData = uni.getStorageSync(cacheKey);

					if (cachedData && cachedData.pages && cachedData.chapters) {
						// 如果有缓存，直接使用缓存数据
						textLayoutStore.pages = cachedData.pages;

						//加载一次
						// textLayoutStore.chapters = cachedData.chapters;


						textLayoutStore.totalPages = cachedData.pages.length;
						textLayoutStore.currentPage = 1;
						textLayoutStore.loadingProgress = 100;
					} else {
						// 如果没有缓存，读取文件内容
						const fileContent = await new Promise((resolve, reject) => {
							plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
								entry.file((file) => {
									const reader = new plus.io.FileReader();
									reader.onload = function(e) {
										resolve(e.target.result);
									};
									reader.onerror = function(e) {
										reject(e);
									};
									reader.readAsText(file, 'UTF-8');
								});
							}, (error) => {
								console.error('文件解析失败：', error);
								reject(error);
							});
						});

						if (fileContent) {
							await textLayoutStore.loadTextContent(fileContent);
						} else {
							throw new Error('文件内容为空');
						}
					}
				} catch (error) {
					console.error('读取文件失败：', error);
					throw error;
				}
			} else {
				// 静态文件使用原来的方式
				const filePath = plus.io.convertLocalFileSystemURL('_www/static/d.txt');
				await textLayoutStore.loadTextFile(filePath);
			}
			// #endif

			// #ifdef H5
			await textLayoutStore.loadTextFile('./static/d.txt');
			// #endif

			// 监听屏幕旋转
			uni.onWindowResize(() => {
				textLayoutStore.initLayout();
			});
		} catch (error) {
			console.error('页面初始化错误:', error);
			loading.value = false;
			// 显示错误提示
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none',
				duration: 2000
			});
		}

		// 初始化时间并设置定时器
		updateTime() // 立即更新一次
		setInterval(updateTime, 60000) // 每分钟更新一次
		
		// 获取电量信息
		getquantity()
		
		// 定时更新电量信息 (每分钟更新一次)
		setInterval(getquantity, 6005000)

		// 监听电量变化（需要在App平台支持）
		if (uni.onBatteryInfoChange) {
			uni.onBatteryInfoChange((res) => {
				batteryLevel.value = res.level
				isCharging.value = res.isCharging
			})
		}
	});

	// 点击事件处理函数
	const handleClick = (e) => {
		// 获取点击位置
		const clickX = e.touches[0].clientX;

		// 发送点击事件，用于语音朗读功能处理
		console.log('发送novelPageClick事件前，isVoiceread:', store.isVoiceread);
		uni.$emit('novelPageClick', e);
		console.log('发送novelPageClick事件后，isVoiceread:', store.isVoiceread);
		
		// 如果语音朗读正在进行，不处理其他点击逻辑
		if (store.isVoiceread || voiceReadStore?.isReading) {
			console.log('语音朗读正在进行，跳过其他点击处理');
			return;
		}
		
		// 检查是否有菜单引用
		if (!menuRef.value) {
			return;
		}

		if (!store.isMenu) {
			if (store.isTiming) {
				store.isTiming = false;
				store.isVoiceread = true;
				return;
			}
			// 只关闭非语音朗读的组件
			if (store.isCatalogue || store.isBrightness || store.isReadsetting || store.isPageway) {
				console.log('关闭非语音朗读组件');
				store.isCatalogue = false;
				store.isBrightness = false;
				store.isReadsetting = false;
				store.isPageway = false;
				return;
			}

			// 计算中间区域范围
			const middleAreaRatio = 0.25;
			const leftBoundary = textLayoutStore.screenWidth * middleAreaRatio;
			const rightBoundary = textLayoutStore.screenWidth * (1 - middleAreaRatio);

			if (clickX < leftBoundary) {
				// 左侧区域 - 上一页
				textLayoutStore.previousPage();
			} else if (clickX > rightBoundary) {
				// 右侧区域 - 下一页
				textLayoutStore.nextPage();
			} else {
				// 中间区域 - 显示菜单
				store.isMenu = true;
				nextTick(() => {
					if (menuRef.value) {
						menuRef.value.showMenus();
					}
				});
			}
		} else {
			// 菜单显示时的处理
			if (menuRef.value) {
				menuRef.value.hideMenus();
				setTimeout(() => {
					store.isMenu = false;
				}, 300);
			}
		}
	};

	// 字体大小变化处理
	const handleFontSizeChange = (size) => {
		textLayoutStore.updateFontSize(size);
	};
</script>

<style lang="scss">
	@import '/common/novel/novel.scss';

	.novel-content {
		width: 100vw;
		height: calc(100vh - 40px);
		// background-color: #333;
		overflow: hidden;
		position: relative;
		padding: 20px 0;

		.loading-overlay {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			// background-color: var(--page-color);
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 999;

			.loading-content {
				text-align: center;

				text {
					font-size: 16px;
					color: #666;
				}
			}
		}

		text {
			display: block;
			color: #333;
			white-space: pre-wrap;
			word-wrap: break-word;
		}

		.chapter-title {
			position: fixed;
			left: 16px;
			top: 16px;
			font-size: 14px;
			color: #666;
			opacity: 0.8;
			// z-index: 1;
			pointer-events: none;
		}

		.context {
			// margin-top: 20px;
			display: flex;
			margin: auto;
			margin-top: 20px;
		}

		.reading-progress {
			width: calc(100vw - 40px);
			position: fixed;
			display: flex;
			justify-content: space-between;
			align-items: center;
			left: 16px;
			bottom: 16px;
			font-size: 12px;
			color: #666;
			opacity: 0.8;
			// z-index: 1;
			pointer-events: none;
			
			text {
				display: inline-block;
				margin: 0 4px;
			}
		}
	}

	.glass-effect {
		/* 护眼底色 */
		background: rgba(199, 237, 204, 0.8);
		/* 模糊效果（核心） */
		backdrop-filter: blur(10px);
		/* 兼容老版本写法（可选） */
		-webkit-backdrop-filter: blur(10px);
		/* 边框/圆角优化 */
		border-radius: 12px;
		/* 内容内边距，避免文字贴边 */
		/* 让元素更通透（可选） */
		box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.3);
	}
</style>